In React, a PureComponent
is a class component that is optimized for performance by implementing a shallow comparison of props and
state. It is a subclass of the regular React Component
class and provides a default implementation of the
shouldComponentUpdate
method.
The shouldComponentUpdate
method is responsible for determining whether a component should re-render or not. By default, it returns
true and triggers a re-render every time the component receives new props or state. However, PureComponent
overrides this method and
performs a shallow comparison of the current and next props and state. If there are no changes, it prevents unnecessary re-renders by returning
false.
Therefore, defining a shouldComponentUpdate
method while extending PureComponent
is redundant and should be avoided. By
not defining shouldComponentUpdate
, you allow React.PureComponent
to handle the optimization for you.
class MyComponent extends React.PureComponent { // Noncompliant
shouldComponentUpdate() {
// does something
}
render() {
return <div>Hello!</div>
}
}
You should either remove the redundant method shouldComponentUpdate
or turn your component into a regular one by extending
Component
.
class MyComponent extends React.Component {
shouldComponentUpdate() {
// does something
}
render() {
return <div>Hello!</div>
}
}